//
//  CollectionPictureViewController.m
//  BSLCar
//
//  Created by dlios on 15/6/3.
//  Copyright (c) 2015年 lyz. All rights reserved.
//

#import "CollectionPictureViewController.h"
#import "LCModel.h"
#import <UIImageView+WebCache.h>
#import "UMSocial.h"
#import <SDImageCache.h>
#import "PictureCollectionViewCell.h"

@interface CollectionPictureViewController () <UICollectionViewDataSource, UICollectionViewDelegate>

@property (nonatomic, retain) UICollectionView *collectionView;
@property (nonatomic, retain) UILabel *nameLabel;
@property (nonatomic, retain) UILabel *indexLabel;
@property (nonatomic, retain) UIImageView *imageview;

@end

@implementation CollectionPictureViewController

- (void)dealloc
{
    [_dataArray release];
    [_serid release];
    [_typeId release];
    [_collectionView release];
    [_nameLabel release];
    [_indexLabel release];
    [_imageview release];
    [super dealloc];
}

- (void)viewWillDisappear:(BOOL)animated {
    [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleDefault animated:YES];
}

- (void)tapGesture {
    [self.navigationController popViewControllerAnimated:YES];
    [self.navigationController setNavigationBarHidden:NO];
}

- (void)viewDidLoad {
    [super viewDidLoad];

    UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapGesture)];
    [self.view addGestureRecognizer:tapGesture];
    [tapGesture release];
    
    
    [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent animated:YES];
    
    UICollectionViewFlowLayout *flowlayout = [[UICollectionViewFlowLayout alloc] init];
    flowlayout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    flowlayout.minimumLineSpacing = 0;
    flowlayout.itemSize = self.view.bounds.size;
    
    self.collectionView = [[UICollectionView alloc] initWithFrame:self.view.bounds collectionViewLayout:flowlayout];
    self.collectionView.delegate = self;
    self.collectionView.dataSource = self;
    [self.view addSubview:self.collectionView];
    self.collectionView.pagingEnabled = YES;

    self.collectionView.bounces = NO;
    self.collectionView.backgroundColor = [UIColor blackColor];
    [self.collectionView registerClass:[PictureCollectionViewCell class] forCellWithReuseIdentifier:@"collectionCell"];
    
    NSIndexPath *indexPath = [NSIndexPath indexPathForItem:self.index inSection:0];
    
    [self.collectionView scrollToItemAtIndexPath:indexPath atScrollPosition:UICollectionViewScrollPositionCenteredHorizontally animated:YES];
    
    self.view.backgroundColor = [UIColor blackColor];
    [self setNeedsStatusBarAppearanceUpdate];
    
    [self.navigationController setNavigationBarHidden:YES];
    
    self.nameLabel = [[UILabel alloc] initWithFrame:CGRectMake(20, 20, self.view.bounds.size.width - 20, 20)];
    self.nameLabel.textAlignment = NSTextAlignmentCenter;
    self.nameLabel.textColor = [UIColor whiteColor];
    LCModel *md = [self.dataArray objectAtIndex:self.index];
    self.nameLabel.text = md.specname;
    [self.view addSubview:self.nameLabel];
    
    self.indexLabel = [[UILabel alloc] initWithFrame:CGRectMake(100, self.view.bounds.size.height - 40, self.view.bounds.size.width - 200, 20)];
    self.indexLabel.textAlignment = NSTextAlignmentCenter;
    self.indexLabel.textColor = [UIColor whiteColor];
    self.indexLabel.text = [NSString stringWithFormat:@"%ld/%ld", self.index + 1, self.piccount];
    [self.view addSubview:self.indexLabel];
    
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    button.frame = CGRectMake(20, self.view.bounds.size.height - 50, 30, 30);
    [button setImage:[UIImage imageNamed:@"iconfont-xz"] forState:UIControlStateNormal];
    [self.view addSubview:button];
    [button addTarget:self action:@selector(baocun:) forControlEvents:UIControlEventTouchUpInside];
    
    UIButton *button2 = [UIButton buttonWithType:UIButtonTypeCustom];
    button2.frame = CGRectMake(self.view.bounds.size.width - 60, self.view.bounds.size.height - 50,30, 30);
    [button2 setImage:[UIImage imageNamed:@"iconfont-fx"] forState:UIControlStateNormal];
    [self.view addSubview:button2];
    [button2 addTarget:self action:@selector(fenxiang) forControlEvents:UIControlEventTouchUpInside];
    
    [flowlayout release];
    [_collectionView release];
    [_nameLabel release];
    [_indexLabel release];
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    PictureCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"collectionCell" forIndexPath:indexPath];
    LCModel *model = [self.dataArray objectAtIndex:indexPath.row];
    self.index = indexPath.row;
    
    self.nameLabel.text = model.specname;
    self.indexLabel.text = [NSString stringWithFormat:@"%ld/%ld", self.index + 1, self.piccount];
    [cell.imageview sd_setImageWithURL:[NSURL URLWithString:model.picurl] placeholderImage:[UIImage imageNamed:@"pict"]];
    self.imageview = cell.imageview;
    return cell;
}

- (void)collectionView:(UICollectionView *)collectionView willDisplayCell:(UICollectionViewCell *)cell forItemAtIndexPath:(NSIndexPath *)indexPath {
    if ((self.index + 59) / 60 == self.pageindex && self.pageindex < self.pagecount) {
        self.pageindex++;
        [self parserUrlRequest];
    }
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return self.dataArray.count;
}

- (void)baocun:(UIButton *)sender {
    UIImageWriteToSavedPhotosAlbum(self.imageview.image, self, @selector(imageSavedToPhotosAlbum:didFinishSavingWithError:contextInfo:), nil);
}

- (void)imageSavedToPhotosAlbum:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo
{
    if (!error) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"保存成功" message:nil delegate:nil cancelButtonTitle:@"取消" otherButtonTitles:nil];
        [alert show];
        [self.view addSubview:alert];
        [alert release];
    } else {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"保存失败" message:nil delegate:nil cancelButtonTitle:@"取消" otherButtonTitles:nil];
        [alert show];
        [self.view addSubview:alert];
        [alert release];
    }
}

- (void)fenxiang {
    [UMSocialSnsService presentSnsIconSheetView:self
                                         appKey:@"556343f267e58ed117001f59"
                                      shareText:self.nameLabel.text
                                     shareImage:self.imageview.image
                                shareToSnsNames:[NSArray arrayWithObjects:UMShareToSina,nil]
                                       delegate:nil];
}


- (void)parserUrlRequest { //  cg 1 外观 10中控  3座椅  12其他
    NSString *string = @"http://baojiac.qichecdn.com/v3.5.5/cars/pics-a2-pm2-v3.9.1-ss";
    string = [NSString stringWithFormat:@"%@%@-sp0-cg%@-cl0-p%ld-s60.html", string, self.serid, self.typeId, self.pageindex];
//    NSLog(@"~~~%ld, ,%ld", self.index,self.pageindex);
    NSURL *url = [NSURL URLWithString:string];
    NSURLRequest *request = [NSURLRequest requestWithURL:url cachePolicy:NSURLRequestReturnCacheDataElseLoad timeoutInterval:20];
    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
        if (!connectionError) {
            NSDictionary *diction = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
            NSDictionary *dict = [diction objectForKey:@"result"];
            NSArray *array = [dict objectForKey:@"piclist"];
            self.piccount = [[dict objectForKey:@"rowcount"] integerValue];
            for (NSDictionary *dic in array) {
                LCModel *model = [LCModel getLCModel];
                model.picurl = [dic objectForKey:@"smallpic"];
                model.specname = [dic objectForKey:@"specname"];
                [self.dataArray addObject:model];
                [self.collectionView reloadData];
            }
        }
    }];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
